<template>
  <div class="home">
    <!-- 主题页面布局 -->
    <el-container class="home-container">
      <!-- 侧边栏 -->
      <el-aside width="200px">
        <!-- 头像区域 -->
        <div class="icon">
          <!-- require 解决图片加载失败 -->
          <el-image :src="require('../assets/img/logo.png')"></el-image>
          <h1 :style="{ margin: 0 }">VB Blog</h1>
        </div>
        <!-- 菜单区域 -->
        <!-- 系统管理菜单 -->
        <template v-if="activeHeaderMenu == 'admin'">
          <el-menu
            background-color="rgb(47, 64, 86)"
            text-color="#fff"
            active-text-color="#409EFF"
            menu-trigger="hover"
            router
            :default-active="defaultMenu"
            :default-openeds="['1', '2']"
          >
            <el-submenu
              v-for="item in adminMenuList"
              :key="item.id"
              :index="item.id"
            >
              <template slot="title">
                <i :class="item.icon"></i>
                <span>{{ item.name }} </span>
              </template>
              <el-menu-item
                v-for="ite in item.children"
                :key="ite.id"
                :index="ite.path"
              >
                <i :class="ite.icon"></i>{{ ite.menuName }}</el-menu-item
              >
            </el-submenu>
          </el-menu>
        </template>
        <!-- 文章管理菜单 -->
        <template v-else>
          <el-menu
            background-color="rgb(47, 64, 86)"
            text-color="#fff"
            active-text-color="#409EFF"
            menu-trigger="hover"
            router
            :default-active="defaultMenu"
          >
            <el-menu-item
              v-for="item in blogMenuList"
              :key="item.id"
              :index="item.path"
            >
              <i :class="item.icon"></i>{{ item.menuName }}</el-menu-item
            >
          </el-menu>
        </template>
      </el-aside>
      <el-container>
        <!-- 头部区域 -->
        <el-header style="height: 95px">
          <!-- 两个菜单 -->
          <div class="header-box">
            <!-- <div class="header-box-item">折叠？</div> -->
            <div
              :class="[
                'header-box-item',
                activeHeaderMenu == 'admin' ? 'active' : ''
              ]"
              @click="changeMenu('admin')"
            >
              后台管理
            </div>
            <div
              :class="[
                'header-box-item',
                activeHeaderMenu == 'article' ? 'active' : ''
              ]"
              @click="changeMenu('article')"
            >
              博客管理
            </div>
          </div>
          <!-- 登录的角色 -->
          <div class="user">
            <el-avatar :size="30" icon="el-icon-user-solid"></el-avatar>
            <el-dropdown
              trigger="hover"
              @command="clickUser"
              placement="bottom-start"
            >
              <span> {{ username }} </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="1">基本资料</el-dropdown-item>
                <el-dropdown-item command="2">修改密码</el-dropdown-item>
                <el-dropdown-item command="3">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>

          <div class="tab-title">
            <ul>
              <li
                @click="changeTab('welcome')"
                :class="[activeTab == 'welcome' ? 'active-tab' : '']"
              >
                <div
                  :class="[
                    'circle',
                    activeTab == 'welcome' ? 'active-tab-circle' : ''
                  ]"
                ></div>
                首页
              </li>
              <li
                v-for="item in tabList"
                :key="item.id"
                @click="changeTab(item)"
                :class="[activeTab.id == item.id ? 'active-tab' : '']"
              >
                <div
                  :class="[
                    'circle',
                    activeTab.id == item.id ? 'active-tab-circle' : ''
                  ]"
                ></div>
                {{ item.name }}
                <div class="close">
                  <i
                    class="el-icon-circle-close"
                    @click.stop="closeTab(item)"
                  ></i>
                </div>
              </li>
            </ul>

            <div class="closeTabsButton" @click="closeTabs">
              <i class="el-icon-circle-close"></i>
            </div>
          </div>
        </el-header>
        <!-- 主体 -->
        <el-main>
          <keep-alive>
            <router-view></router-view>
          </keep-alive>
        </el-main>
      </el-container>
    </el-container>

    <!-- 修改用户资料弹窗 -->
    <el-dialog
      title="修改用户资料"
      :visible.sync="isUserInfoDialogVisible"
      width="50%"
      :before-close="handleClose"
      @close="closeUserInfoDialog"
    >
      <!-- 用户基本信息表单 -->
      <el-form
        :model="userForm"
        :rules="userFormRules"
        ref="userFormRef"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="userForm.username"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input
            v-model="userForm.nickname"
            placeholder="请输入昵称"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="emali">
          <el-input
            v-model="userForm.emali"
            placeholder="请输入邮箱"
          ></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="isUserInfoDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="isUserInfoDialogVisible = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 修改密码弹窗 -->
    <el-dialog
      title="修改密码"
      :visible.sync="isUserPwdDialogVisible"
      width="50%"
      :before-close="handleClose"
      @close="closeUserPwdDialog"
    >
      <!-- 用户密码表单 -->
      <el-form
        :model="userPwdForm"
        :rules="userPwdFormRules"
        ref="userPwdFormRef"
        label-width="100px"
      >
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input
            type="password"
            v-model="userPwdForm.oldPassword"
            placeholder="请输入旧密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            type="password"
            v-model="userPwdForm.newPassword"
            placeholder="请输入新密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="againPassword">
          <el-input
            type="password"
            v-model="userPwdForm.againPassword"
            placeholder="请再次输入新密码"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isUserPwdDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="isUserPwdDialogVisible = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'home',
  components: {},

  created() {
    var zhangsan = 111

    console.log(zhangsan)

    //获取所有菜单列表
    this.adminMenuList.forEach((item) => {
      item.children.forEach((menu_item) => {
        this.allMenuList.push(menu_item)
      })
    })

    this.blogMenuList.forEach((item) => {
      this.allMenuList.push(item)
    })
  },
  data() {
    var oldPwd = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入旧密码'))
      } else {
        callback()
      }
    }
    var newPwd = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入新密码'))
      } else {
        if (this.userPwdForm.againPassword !== '') {
          this.$refs.userPwdFormRef.validateField('againPassword')
        }
        callback()
      }
    }
    var againPwd = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else if (value !== this.userPwdForm.newPassword) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }

    return {
      //激活的菜单，上方
      activeHeaderMenu: 'admin',
      username: 'xianyu',
      //默认激活的菜单path
      defaultMenu: '',
      //激活的标签
      activeTab: '',
      //标签列表
      tabList: [],

      isUserInfoDialogVisible: false,
      isUserPwdDialogVisible: false,

      //点击用户的类型
      usertype: 'userinfo',

      // 用户信息表单
      userForm: {
        username: '',
        nickname: '',
        emali: ''
      },
      // 用户密码表单
      userPwdForm: {
        oldPassword: '',
        newPassword: '',
        againPassword: '',
        userId: 0
      },

      // 验证规则
      userFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        emali: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change']
          }
        ]
      },
      // 用户密码验证规则
      userPwdFormRules: {
        oldPassword: [
          { required: true, message: '请输入旧密码', trigger: 'blur' },
          { validator: oldPwd, trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { validator: newPwd, trigger: 'blur' }
        ],
        againPassword: [
          { required: true, message: '请再次输入新密码', trigger: 'blur' },
          { validator: againPwd, trigger: 'blur' }
        ]
      },

      // 管理员菜单列表
      adminMenuList: [
        {
          id: '1',
          icon: 'el-icon-setting',
          name: '系统管理',
          children: [
            {
              id: 11,
              path: 'user',
              icon: 'el-icon-s-custom',
              menuName: '用户管理'
            },
            {
              id: 12,
              path: 'role',
              icon: 'el-icon-s-custom',
              menuName: '角色管理'
            },
            {
              id: 13,
              path: 'menu',
              icon: 'el-icon-menu',
              menuName: '菜单管理'
            },
            {
              id: 14,
              path: 'notice',
              icon: 'el-icon-s-claim',
              menuName: '公告管理'
            }
          ]
        },
        {
          id: '2',
          icon: 'el-icon-data-board',
          name: '系统工具',
          children: [
            {
              id: 15,
              path: 'accessLog',
              icon: 'el-icon-view',
              menuName: '访问日志'
            },
            {
              id: 16,
              path: 'handleLog',
              icon: 'el-icon-notebook-2',
              menuName: '操作日志'
            },
            {
              id: 17,
              path: 'interface',
              icon: 'el-icon-notebook-2',
              menuName: '接口文档'
            }
          ]
        }
      ],

      // 文章菜单列表
      blogMenuList: [
        {
          id: 21,
          path: 'addArticle',
          icon: 'el-icon-edit',
          menuName: '文章发布'
        },
        {
          id: 22,
          path: 'article',
          icon: 'el-icon-notebook-1',
          menuName: '文章管理'
        },
        {
          id: 23,
          path: 'classify',
          icon: 'el-icon-s-operation',
          menuName: '分类管理'
        },
        {
          id: 24,
          path: 'tag',
          icon: 'el-icon-collection-tag',
          menuName: '标签管理'
        },
        {
          id: 25,
          path: 'comment',
          icon: 'el-icon-chat-dot-round',
          menuName: '评论管理'
        },
        {
          id: 26,
          path: 'leaveMessage',
          icon: 'el-icon-chat-line-square',
          menuName: '留言管理'
        },
        { id: 27, path: 'link', icon: 'el-icon-link', menuName: '友联管理' }
      ],
      allMenuList: []
    }
  },

  mounted() {
    this.activeTab = 'welcome'

    //打印窗口大小
    let h = document.body.clientHeight
    console.log('高度:' + h)
  },

  watch: {
    //监听路由改变
    $route(to, from) {
      if (to !== from) {
        //TODO  路由改变，更改激活的菜单和激活的tab

        this.changeActiveDefaultMenu(to.name, to.meta.headerMenu)
      }
    }
  },

  methods: {
    // 改变菜单
    changeMenu(val) {
      this.activeHeaderMenu = val
    },

    //修改资料、密码，退出登录
    /**
     * 基本资料   1
     * 修改密码   2
     * 退出登录   3
     */
    clickUser(val) {
      switch (val) {
        case '1':
          this.usertype = 'userinfo'
          this.isUserInfoDialogVisible = true

          break
        case '2':
          this.usertype = 'userpassword'
          this.isUserPwdDialogVisible = true
          break
        case '3':
          this.$router.push('login')

          break

        default:
          console.log('异常')
          break
      }
    },
    // 添加标签
    addTab(menuItem, activeMenuName) {
      for (let index = 0; index < this.tabList.length; index++) {
        if (this.tabList[index].id == menuItem.id) return
      }

      this.tabList.push({
        id: menuItem.id,
        path: menuItem.path,
        name: menuItem.menuName,
        menuName: activeMenuName
      })
    },
    // 关闭标签
    closeTab(tab) {
      //查找需要删除的id
      let index = this.tabList.findIndex((item) => {
        return item.id == tab.id
      })

      this.tabList.splice(index, 1)

      //删除自己，回到欢迎页
      if (tab.id == this.activeTab.id) {
        this.$router.push('welcome')
      }
    },
    // 关闭所有标签
    closeTabs() {
      if (this.tabList == []) return

      if (this.activeTab != 'welcome') {
        this.$router.push('welcome')
      }

      this.tabList = []
      this.activeTab = 'welcome'
      this.defaultMenu = ''
    },
    // 改变标签
    changeTab(tab) {
      // 点击首页
      if (tab == 'welcome') {
        if (this.activeTab == 'welcome') return
        this.$router.push(tab)

        return
      }
      // 判断点击自己，不执行下面
      if (this.activeTab.id == tab.id) return
      this.$router.push(tab.path)
    },
    //dialog 关闭前回调
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          done()
        })
        .catch((_) => {})
    },
    // 关闭修改信息dialog
    closeUserInfoDialog() {
      this.$refs.userFormRef.resetFields()
    },

    // 关闭修改密码dialog
    closeUserPwdDialog() {
      this.$refs.userFormRef.resetFields()
    },
    //路由切换时，改变侧边栏的激活项
    changeActiveDefaultMenu(path, headerMenu) {
      //路由跳转首页

      if (path == 'welcome') {
        if (this.activeTab == 'welcome') return

        this.defaultMenu = ''
        this.activeTab = 'welcome'

        return
      }

      this.activeHeaderMenu = headerMenu
      this.defaultMenu = path

      let menuItem = {}
      //根据path，查找菜单信息
      menuItem = this.allMenuList.find((item) => {
        return item.path == path
      })

      //添加tab
      let tab = {
        id: menuItem.id,
        path: menuItem.path,
        name: menuItem.menuName,
        menuName: headerMenu
      }

      // 添加后，高亮选中tab
      this.activeTab = tab

      //防止重复添加
      let isLike = this.tabList.findIndex((item) => {
        return item.id == tab.id
      })
      if (isLike != -1) return

      this.tabList.push(tab)
    }
  }
}
</script>

<style lang="less" scoped>
.home {
  height: 100%;
}

.home-container {
  height: 100%;
}

.el-aside {
  background-color: rgb(47, 64, 86);
  color: rgb(255, 255, 255);

  .icon {
    width: 200px;
    height: 60px;
    text-align: center; //文字居中
    background-color: rgb(36, 51, 70);
    display: flex; //弹性布局
    flex-direction: row;
    align-items: center;
    justify-content: center;
    .el-image {
      width: 40px;
      height: 40px;
      margin-right: 10px;
    }
  }

  .el-submenu {
    min-width: 200px;
  }
  .el-menu-item {
    min-width: 200px;
  }
}

// 头部
.el-header {
  padding: 0;
  background-color: rgb(26, 160, 148);

  .header-box {
    height: 60px;
    display: flex;
    align-items: center;

    .header-box-item {
      width: 100px;
      height: 60px;
      cursor: pointer; //鼠标悬浮变小手
      line-height: 60px; //设置行高，达到居中效果
      text-align: center;
      font-size: 14px;
      color: #fff;
    }
  }

  .user {
    margin-right: 20px;

    height: 60px;
    width: 100px;
    line-height: 60px;
    text-align: center;

    position: absolute !important;
    right: 0;
    top: 0;
  }
}

// 动态选中的类
.active {
  background-color: rgb(25, 121, 113);
}

.active-tab {
  color: dimgray !important;
}
.active-tab-circle {
  background-color: #1aa094 !important;
}

.el-main {
  padding: 0;
  background-color: #e9eef3;
}

.tab-title {
  position: relative;
  background-color: white;
  height: 35px;

  position: relative;

  ul {
    margin: 0;

    height: 35px;
    border: 1px solid whitesmoke;
    overflow: auto;

    li {
      .circle {
        display: inline-block;
        width: 9px;
        height: 9px;
        background-color: #acafb1;
        border-radius: 30px;
        margin-right: 5px;
      }

      .close {
        display: inline-block;
      }

      i:hover {
        background-color: tomato;
        color: white !important;
      }

      i {
        font-size: 15px;
        border-radius: 50px;
      }

      color: #acafb1;

      cursor: pointer; //鼠标悬浮变小手
      height: 35px;
      padding: 0 15px !important;
      border-right: 1px solid whitesmoke;

      list-style: none; /* 将默认的列表符号去掉 */
      padding: 0; /* 将默认的内边距去掉 */
      margin: 0; /* 将默认的外边距去掉 */
      float: left; /* 往左浮动 */
      display: block;
      text-align: center; /* 居中对齐文字 */
      line-height: 35px; /* 设置行高，将行高和高度设置同一个值，可以让单行文本垂直居中 */
      text-align: center;
    }
  }

  .closeTabsButton {
    width: 35px;
    height: 35px;
    // background-color: orangered;

    position: absolute;
    top: 0;
    right: 20px;

    cursor: pointer; //鼠标悬浮变小手

    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 25px;
  }
}

.el-dropdown {
  color: #fff !important;
  cursor: pointer; //鼠标悬浮变小手
}

.el-avatar {
  margin-right: 8px;
  overflow: inherit;
}
</style>
